package com.example.servlet;

import com.example.dao.UserDAO;
import com.example.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserDAO userDAO;

    @Override
    public void init() throws ServletException {
        try {
            userDAO = new UserDAO();
        } catch (Exception e) {
            throw new ServletException("初始化用户 DAO 失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirm_password");
        String email = request.getParameter("email");

        // 验证输入是否为空
        if (username == null || username.trim().isEmpty()) {
            request.setAttribute("error", "请输入用户名");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }
        
        if (password == null || password.trim().isEmpty()) {
            request.setAttribute("error", "请输入密码");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }
        
        if (email == null || email.trim().isEmpty()) {
            request.setAttribute("error", "请输入邮箱地址");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // 验证邮箱格式
        if (!isValidEmail(email)) {
            request.setAttribute("error", "请输入有效的邮箱地址");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // 验证密码匹配
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "密码不匹配");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        try {
            // 检查用户名是否已存在
            if (userDAO.getUserByUsername(username) != null) {
                request.setAttribute("error", "用户名已存在");
                request.getRequestDispatcher("register.jsp").forward(request, response);
                return;
            }

            // 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setEmail(email);

            // 注册用户
            if (userDAO.registerUser(newUser)) {
                // 注册成功，自动登录并跳转到主界面
                request.getSession().setAttribute("user", newUser);
                response.sendRedirect("index.jsp");
            } else {
                request.setAttribute("error", "注册失败，请稍后重试");
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库错误: " + e.getMessage());
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
    
    /**
     * 验证邮箱格式是否有效
     */
    private boolean isValidEmail(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        
        // 简单的邮箱格式验证正则表达式
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        return email.matches(emailRegex);
    }
}